class Solution {
public:
    bool isValid(string s) {
        if(s.size()%2!=0) return false;
        stack<char> brackets;
        int len = s.size();
        for (int i = 0; i < len; ++i) {
            //开括号压入栈
            if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
                brackets.push(s[i]);
            }else{
                //闭括号与开括号数量不同，说明无效
                if (brackets.empty()) return false;
                //闭括号与栈顶括号不同，说明无效
                if ((s[i] == '}' && brackets.top() != '{') 
                    || (s[i] == ']' && brackets.top() != '[') 
                    || (s[i] == ')' && brackets.top() != '(')){
                    return false;
                }else{
                    brackets.pop();
                }
            }
        }
        return brackets.empty();
    }
};